<script setup lang="ts">
import { reactive, ref, unref } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'

import { useForm } from '@/hooks/web/useForm'

import { required } from '@/utils/formRules'

// import { adminFaUserListApi } from '@/api/fa/user'
import { ucMyOrgListApi } from '@/api/cy/Loanapply'

import { sysDictRelsApi } from '@/api/dict'

// import Edit from '../components/Edit.vue'
import { ucDeptListApi } from '@/api/uc/dept'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { zcAssetSeeApi } from '@/api/cy/Assets'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label

/****************************** 变量 start ******************************/
const userInfo: any = wsCache.get('userInfo')
const data = ref<any>({})
data.value.customer_name = userInfo.default_org_name
data.value.customer_id = userInfo.default_org_id
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举

const fileRef = ref()

const rules = reactive({
  pasture_org_id: [required],
  breed: [required],
  breed_sub: [required],
  amount: [required],
  pasture_dept_name: [required],
  number: [required],
  loan_no: [required]
})

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object,
    default: () => null
  }
})

/****************************** 组件参数 end ******************************/

// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcAssetSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data

      await methodsForm.setValues(data.value)
      DeptList(data.value.pasture_org_id)

      console.log(props.id, data.value, '11111')
      // DeptList(data.value.pasture_org_id)
    }
  } else {
    data.value.state = '1'
    data.value.selected = []
    data.value.fileData = []
    await methodsForm.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    console.log(res)
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    console.log(dictRelsData.value, 'dictRelsData.value')
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
let formData = reactive([])
const breedChange = async (value) => {
  await breedGetSub(value)
  formData = await methodsForm.getFormData()
  console.log(formData, 'formData')
  await methodsForm.setValues({ ...formData, breed_sub: '' })
}

const onCustomer = async (value: String) => {
  console.log(value, 'admin_org_id')
  if (value != data.value.pasture_org_id) {
    // data.value.pasture_org_id = Number(value)
    data.value.pasture_org_id = value
    newTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_dept_name = ''
    data.value.insurance_type = ''
    data.value.allCheck = false
    DeptList(value)
    // getListAsset()
  }
  await methodsForm.setValues(data.value)
}
let newTreeData = ref<any[]>([])
const DeptList = async (val) => {
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
  }
}

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  const file = unref(fileRef) //附件
  let fileData = file?.getData()
  console.log(fileData, '附件')
  return { ...formData, fileData: fileData, selected: data.value.selected }
}

/****************************** 明细配置 start ******************************/

/****************************** 明细配置 end ******************************/
const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: ucMyOrgListApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } },
        { field: 'org_id', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer,
      disabled: true
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      disabled: false
      // onChange: onDept
    }
  },
  {
    field: 'breed',
    label: '畜别',
    component: 'Select',
    componentProps: {
      options: dict.breed,
      onChange: breedChange
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    component: 'Select',
    componentProps: {
      options: breedSubData
    }
  },
  {
    field: 'sex',
    label: '性别',
    component: 'Select',
    componentProps: {
      options: dict.animal_sex
    }
  },
  {
    field: 'is_die',
    label: '是否死亡',
    component: 'Select',
    componentProps: {
      options: dict.is
    }
  },
  {
    field: 'purpose',
    label: '用途',
    component: 'Select',
    componentProps: {
      options: dict.purpose
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    component: 'Input',
    colProps: {
      span: 10
    }
  },
  {
    field: 'purchase_price',
    label: '采购价',
    component: 'Input',
    colProps: {
      span: 10
    }
  },
  {
    field: 'all_purchase_price',
    label: '综合采购价',
    component: 'Input',
    colProps: {
      span: 10
    }
  },
  {
    field: 'other_fees',
    label: '其他费用',
    component: 'Input',
    colProps: {
      span: 10
    }
  }
]
const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema: schema
})

defineExpose({
  elFormRef,
  getFormData,
  data
})
/****************************** 初始化 start ******************************/

const init = async () => {
  await getMedicalOrderSee()
  await getDictRels()
  // console.log(data.value)
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}

init()
/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="registerForm" :data="data" />
    </ContentWrap>
  </div>
</template>
